package ar.com.pragmatia.lanacion;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.UUID;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.Images;
import android.provider.MediaStore.Images.Media;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.Toast;
import ar.com.pragmatia.lanacion.app.App;
import ar.com.pragmatia.lanacion.data.Client;
import ar.com.pragmatia.lanacion.data.Visit;

public class NewVisitActivity extends LaNacionActivity {

	private Spinner spnReason;
	private Spinner spnResult;
	private Spinner spnClaim;
	private Spinner spnItemsDelivered;
	private EditText txtContact;
	private EditText txtDate;
	private EditText txtTime;
	private EditText txtObservation;
	private EditText txtNextVisitDate;
	private EditText txtNextVisitTime;
	private AutoCompleteTextView txtClientAutocomplete;

	private Date date, nextVisitDate = new Date();
	private Visit visit;
	private UUID unique;
	private Button btnAddVisit;

	private ImageView imageView;
	private Bitmap imageBitmap;
	private String tmpImage;
	private final int CAMERA_PIC_REQUEST = 1337;
	private Button btnTakePicture;
	private Context appContext;
//	private LocationListener locationListener;
	private LocationListener locationListener2;
	private LocationManager locationManager;
	private int trys;
	private ProgressDialog progressDialog;

	private static final int DATE_DIALOG_ID = 0;
	private static final int TIME_DIALOG_ID = 1;
	private static final int DATE_NEXT_VISIT_DIALOG_ID = 2;
	private static final int TIME_NEXT_VISIT_DIALOG_ID = 3;

	private OnClickListener takeFoto = new OnClickListener() {

		public void onClick(View v) {
			Intent cameraIntent = new Intent(
					android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
			File imageDirectory = new File((new File(tmpImage)).getParent());
			String path = imageDirectory.toString().toLowerCase();
			// String name = imageDirectory.getName().toLowerCase();

			ContentValues values = new ContentValues();
			values.put(Media.TITLE, "Image");
			values.put(Images.Media.BUCKET_ID, path.hashCode());
			// values.put(Images.Media.BUCKET_DISPLAY_NAME, name);

			values.put(Images.Media.MIME_TYPE, "image/jpeg");
			// values.put(Media.DESCRIPTION, "Image capture by camera");
			values.put("_data", tmpImage);
			Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI,
					values);
			cameraIntent
					.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, uri);
			cameraIntent.putExtra(
					android.provider.MediaStore.EXTRA_VIDEO_QUALITY, 1);
			startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
		}
	};

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == CAMERA_PIC_REQUEST) {
			final int THUMBNAIL_HEIGHT = 200;

			imageBitmap = BitmapFactory.decodeFile(tmpImage);
			Float width = new Float(imageBitmap.getWidth());
			Float height = new Float(imageBitmap.getHeight());
			Float ratio = width / height;
			imageBitmap = Bitmap.createScaledBitmap(imageBitmap,
					(int) (THUMBNAIL_HEIGHT * ratio), THUMBNAIL_HEIGHT, false);

			imageView.setImageBitmap(imageBitmap);

			// try {
			// HttpFileUploader htfu = new HttpFileUploader(
			// "http://192.168.1.157/test.php");
			// BasicNameValuePair newVar = new BasicNameValuePair("test",
			// "hola!");
			// htfu.addVar(newVar);
			// htfu.addFile("/sdcard/Parki/test.jpg", "laFoto.jpg",
			// "uploadedfile");
			// new Thread(htfu).start();
			// } catch (FileNotFoundException e1) {
			// e1.printStackTrace();
			// } catch (IOException e) {
			// e.printStackTrace();
			// }
		}
	}

	private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			date.setHours(hourOfDay);
			date.setMinutes(minute);
			updateTime();
		}
	};

	private TimePickerDialog.OnTimeSetListener mTimeNextVisitSetListener = new TimePickerDialog.OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			nextVisitDate.setHours(hourOfDay);
			nextVisitDate.setMinutes(minute);
			updateTime();
		}
	};

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			date.setYear(year - 1900);
			date.setMonth(monthOfYear);
			date.setDate(dayOfMonth);
			updateTime();
		}
	};

	private DatePickerDialog.OnDateSetListener mDateNextVisitSetListener = new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			nextVisitDate.setYear(year - 1900);
			nextVisitDate.setMonth(monthOfYear);
			nextVisitDate.setDate(dayOfMonth);
			updateTime();

		}

	};

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.visits_new);

		if (visit == null) {
			visit = new Visit();
		}

		Button btnVisits = (Button) findViewById(R.id.btnVisits);
		if (btnVisits != null) {
			btnVisits.setPressed(true);
		}

		txtContact = (EditText) findViewById(R.id.txtContact);
		txtDate = (EditText) findViewById(R.id.txtDate);
		txtTime = (EditText) findViewById(R.id.txtTime);
		txtObservation = (EditText) findViewById(R.id.txtObservation);
		txtNextVisitDate = (EditText) findViewById(R.id.txtNextVisitDate);
		txtNextVisitTime = (EditText) findViewById(R.id.txtNextVisitTime);
		btnAddVisit = (Button) findViewById(R.id.btnAddVisit);

		unique = UUID.randomUUID();

		tmpImage = "/sdcard/LaNacion/Visit/" + unique + ".jpg";

		btnTakePicture = (Button) findViewById(R.id.btnTakePicture);

		btnTakePicture.setOnClickListener(takeFoto);

		imageView = (ImageView) findViewById(R.id.photoResultView);

		txtClientAutocomplete = (AutoCompleteTextView) findViewById(R.id.txtClientAutocomplete);

		ArrayAdapter<Client> aAdapter = new ArrayAdapter<Client>(this,
				R.layout.list_item);
		aAdapter.addAll((Collection) new Client().find());
		txtClientAutocomplete.setAdapter(aAdapter);

		txtClientAutocomplete.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Object o = arg0.getItemAtPosition(arg2);
				visit.setClientId(((Client) o).getId());

			}

		});
		// .setOnItemSelectedListener(new OnItemSelectedListener() {
		//
		// @Override
		// public void onItemSelected(AdapterView<?> arg0, View arg1,
		// int arg2, long arg3) {
		// Object o = arg0.getItemAtPosition(arg2);
		// App.log("NewVisitActivity", "SelectedItemlistener",
		// o.toString());
		//
		// }
		//
		// @Override
		// public void onNothingSelected(AdapterView<?> arg0) {
		// // TODO Auto-generated method stub
		//
		// }
		//
		// });

		spnReason = (Spinner) findViewById(R.id.spnReason);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.visit_reason_array,
				android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spnReason.setAdapter(adapter);

		spnResult = (Spinner) findViewById(R.id.spnResult);
		adapter = ArrayAdapter.createFromResource(this,
				R.array.visit_result_array,
				android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spnResult.setAdapter(adapter);

		spnClaim = (Spinner) findViewById(R.id.spnClaim);
		adapter = ArrayAdapter
				.createFromResource(this, R.array.visit_claim_array,
						android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spnClaim.setAdapter(adapter);

		spnItemsDelivered = (Spinner) findViewById(R.id.spnItemsDelivered);
		adapter = ArrayAdapter.createFromResource(this,
				R.array.visit_items_delivered_array,
				android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spnItemsDelivered.setAdapter(adapter);

		updateTime();

		txtTime.setOnFocusChangeListener(new OnFocusChangeListener() {

			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					txtTime.clearFocus();
					showDialog(TIME_DIALOG_ID);
				}
			}
		});
		txtNextVisitTime.setOnFocusChangeListener(new OnFocusChangeListener() {

			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					txtNextVisitTime.clearFocus();
					showDialog(TIME_NEXT_VISIT_DIALOG_ID);
				}
			}
		});

		txtDate.setOnFocusChangeListener(new OnFocusChangeListener() {

			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					txtDate.clearFocus();
					showDialog(DATE_DIALOG_ID);
				}
			}
		});
		txtNextVisitDate.setOnFocusChangeListener(new OnFocusChangeListener() {

			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					txtNextVisitDate.clearFocus();
					showDialog(DATE_NEXT_VISIT_DIALOG_ID);
				}
			}
		});

		appContext = this;
		btnAddVisit.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				locationManager = (LocationManager) appContext
						.getSystemService(Context.LOCATION_SERVICE);
				trys = 0;
				progressDialog = ProgressDialog.show(NewVisitActivity.this,
						getString(R.string.wait), getString(R.string.loading),
						true, false);
				// Define a listener that responds to location updates
//				locationListener = new LocationListener() {
//					public void onLocationChanged(Location location) {
//						// Called when a new location is found by the network
//						// location provider.
//						makeUseOfNewLocation(location);
//					}
//
//					public void onStatusChanged(String provider, int status,
//							Bundle extras) {
//					}
//
//					public void onProviderEnabled(String provider) {
//					}
//
//					public void onProviderDisabled(String provider) {
//					}
//				};
				locationListener2 = new LocationListener() {
					public void onLocationChanged(Location location) {
						// Called when a new location is found by the network
						// location provider.
						makeUseOfNewLocation(location);
					}

					public void onStatusChanged(String provider, int status,
							Bundle extras) {
					}

					public void onProviderEnabled(String provider) {
					}

					public void onProviderDisabled(String provider) {
					}
				};

				// Register the listener with the Location Manager to receive
				// location updates
//				locationManager.requestLocationUpdates(
//						LocationManager.NETWORK_PROVIDER, 300, 0,
//						locationListener);
				locationManager
						.requestLocationUpdates(LocationManager.GPS_PROVIDER,
								300, 0, locationListener2);

			}
		});

	}

	private void makeUseOfNewLocation(Location l) {
		App.log("Que", "pasa", trys + " - " + l.getAccuracy());
		if (l.getAccuracy() < 10 || trys >= 10) {
			locationManager.removeUpdates(locationListener2);
			progressDialog.dismiss();
			createVisitFromFields();
			visit.setLocation("(" + l.getLatitude() + ", " + l.getLongitude()
					+ ")");
			if (visit.save(true)) {
				String text = getText(R.string.visit_added).toString();
				int duration = Toast.LENGTH_SHORT * 2;
				Toast toast = Toast.makeText(getApplicationContext(), text,
						duration);
				toast.show();
				Intent index = new Intent().setClass(appContext,
						MainVisitActivity.class);
				startActivity(index);
			}
		}
		trys++;
	}

	private Visit createVisitFromFields() {
		if (visit == null) {
			visit = new Visit();
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		visit.setContact(txtContact.getText().toString());
		visit.setNextVisitDate(sdf.format(nextVisitDate));
		visit.setVisitDate(sdf.format(date));
		visit.setObservation(txtObservation.getText().toString());
		visit.setReason(spnReason.getSelectedItem().toString());
		visit.setResult(spnResult.getSelectedItem().toString());
		visit.setItemsDelivered(spnItemsDelivered.getSelectedItem().toString());
		visit.setClaim(spnClaim.getSelectedItem().toString());
		visit.setUuid(unique.toString());
		return visit;
	}

	protected void updateTime() {
		if (date == null) {
			date = new Date();
		}
		if (nextVisitDate == null) {
			nextVisitDate = new Date();
		}
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
		SimpleDateFormat stf = new SimpleDateFormat("HH:mm");
		txtDate.setText(sdf.format(date));
		txtTime.setText(stf.format(date));
		txtNextVisitDate.setText(sdf.format(nextVisitDate));
		txtNextVisitTime.setText(stf.format(nextVisitDate));
	}

	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case TIME_DIALOG_ID:
			return new TimePickerDialog(this, mTimeSetListener,
					date.getHours(), date.getMinutes(), true);
		case TIME_NEXT_VISIT_DIALOG_ID:
			return new TimePickerDialog(this, mTimeNextVisitSetListener,
					nextVisitDate.getHours(), nextVisitDate.getMinutes(), true);
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, mDateSetListener,
					date.getYear() + 1900, date.getMonth(), date.getDate());
		case DATE_NEXT_VISIT_DIALOG_ID:
			return new DatePickerDialog(this, mDateNextVisitSetListener,
					nextVisitDate.getYear() + 1900, nextVisitDate.getMonth(),
					nextVisitDate.getDate());
		}
		return null;
	}
}
